import { useChatStore } from '@/store'

// 异步队列类（放在合适的工具文件或当前文件顶部）
class AsyncQueue {
  private queue = Promise.resolve()

  // 确保返回类型是 Promise<void>
  enqueue(fn: () => void): Promise<void> {
    const task = this.queue.then(() => fn());  // 返回 Promise<void>
    this.queue = task.catch(() => {});  // 防止队列中断
    return task;
  }
}

const chatQueue = new AsyncQueue()

export function useChat() {
  const chatStore = useChatStore()

  const addChat = async (uuid: number, chat: Chat.Chat) => {
    return chatQueue.enqueue(() => chatStore.addChatByUuid(uuid, chat))
  }

  const updateChat = async (uuid: number, index: number, chat: Chat.Chat) => {
    return chatStore.updateChatByUuid(uuid, index, chat) // 可选是否加队列
  }

  return {
    addChat,
    updateChat
  }
}
